#include "icon_image_provider.h"
#include <QDebug>
#include <QFileInfo>

IconImageProvider::IconImageProvider()
    : QQuickImageProvider(QQuickImageProvider::Pixmap)
{
}

QPixmap IconImageProvider::requestPixmap(const QString &id, QSize *size, const QSize &requestedSize)
{
    // 从 id 中获取文件路径
    QString filePath = id;
    
    // 确定图标大小
    QSize iconSize = requestedSize.isValid() ? requestedSize : QSize(32, 32);
    if (iconSize.width() <= 0) iconSize.setWidth(32);
    if (iconSize.height() <= 0) iconSize.setHeight(32);
    
    // 获取文件信息
    QFileInfo info(filePath);
    QString iconPath;
    
    if (info.isDir()) {
        iconPath = "qrc:/icons/folder.png";
    } else {
        QString suffix = info.suffix().toLower();
        iconPath = QString("qrc:/icons/%1.png").arg(suffix);
    }
    
    // 加载图标
    QPixmap pixmap(iconPath);
    if (pixmap.isNull()) {
        // 如果找不到对应图标，使用默认图标
        pixmap = QPixmap("qrc:/icons/txt.png");
    }
    
    // 缩放到请求的大小
    if (!pixmap.isNull() && pixmap.size() != iconSize) {
        pixmap = pixmap.scaled(iconSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    }
    
    // 设置返回的大小
    if (size) {
        *size = pixmap.size();
    }
    
    return pixmap;
}
